import React, { useState } from 'react';
import { Box, MainButton, makeToast, NotificationBanner, Text } from '@nova-hf/ui';
import { MainColorType } from '@nova-hf/ui/umd/ts/src/styles/vars.css';
import Authentication from 'beta/store/authentication';
import UI from 'beta/store/ui';
import { inject } from 'mobx-react';
import { useRouter } from 'next/router';
import {
  RestrictionLiftStatus,
  RestrictionStatus,
  useCustomerNationalIdQuery,
  useLiftRestrictionMutation,
  useNovaSubscriptionStatusQuery,
  useRestrictionsQuery,
} from 'typings/graphql';
import { useTranslation } from 'utils/i18n';

import { formatDate } from '../../../../utils/helpers';
import ContractDefaultsContainer from '../../../askriftir/[contractId]/containers/ContractDefaultsContainer';

type FiberRestrictionsProps = {
  restriction?: boolean;
  nationalId: string;
  color: MainColorType;
  hasPingAlert: boolean;
  authentication?: Authentication;
  ui?: UI;
  contractId?: string;
  isAlltSaman?: boolean;
};

const FiberRestrictions = ({
  restriction,
  hasPingAlert,
  authentication,
  nationalId,
  contractId,
  isAlltSaman,
  ui,
}: FiberRestrictionsProps) => {
  const { t } = useTranslation('fiber');
  const router = useRouter();
  const isStaff = authentication?.isStaff;
  const isStaffAndNotAlltSaman = isStaff && !isAlltSaman;
  const customerId = router?.query?.customerId ?? '';
  const serviceId = router?.query?.serviceId ?? '';
  const { data } = useCustomerNationalIdQuery({
    variables: { input: { id: customerId?.toString() } },
  });
  const { data: subData } = useNovaSubscriptionStatusQuery({
    variables: { input: { id: contractId ?? '' } },
  });
  const { data: restrictionsData, refetch } = useRestrictionsQuery({
    variables: { serviceId: serviceId?.toString() },
  });
  const isPayer = data?.customer?.nationalId === nationalId;
  const subId = subData?.subscriptionById?.externalId;
  const isStaffOrPayer = isStaff || isPayer;
  const restrictions = restrictionsData?.restrictions;
  const firstUnresolvedRestriction = restrictions?.find(
    (restriction) => restriction?.restrictionStatus === RestrictionStatus.Active,
  );
  const firstHasLiftAlready = firstUnresolvedRestriction?.temporaryRestrictionLifts?.find(
    (lift) => lift?.status === RestrictionLiftStatus.Active,
  );
  const [isShowingLiftForm, setIsShowingLiftForm] = useState(false);
  const [liftError, setLiftError] = useState('');
  const [liftRestriction] = useLiftRestrictionMutation({
    onCompleted() {
      refetch();
      makeToast.success(t('fiber:fiberActivate.activateText'), '');
      setIsShowingLiftForm(false);
    },
    onError(error) {
      if (error instanceof Error)
        makeToast.danger(t('fiber:fiberActivate.failText'), error.message);
      setLiftError(error.message);
    },
  });

  const handleRestrictionLift = async () => {
    await liftRestriction({
      variables: {
        input: {
          serviceId: serviceId?.toString(),
          restrictionId: firstUnresolvedRestriction?.id ?? '',
        },
      },
    });
  };

  if (!restriction || !restrictions) return null;

  if (firstHasLiftAlready && firstHasLiftAlready.liftEnd)
    return (
      <NotificationBanner
        eyebrowText={t('restrictions.banner.eyebrow')}
        description={
          isStaffOrPayer
            ? `${t('restrictions.otherBanner.descriptionOne')} ${formatDate(
                firstHasLiftAlready.liftEnd,
                'dd.MM.yyyy - HH:mm',
              )}${t('restrictions.otherBanner.descriptionOnePartTwo')}`
            : `${t('restrictions.otherBanner.descriptionTwo')} ${formatDate(
                firstHasLiftAlready.liftEnd,
                'dd.MM.yyyy - HH:mm',
              )}`
        }
        icon="lockOpen"
        color={ui?.serviceColor}
        {...(isStaffOrPayer && {
          mainButtonColored: {
            icon: 'longArrowRight',
            text: t('restrictions.banner.payButton'),
            onClick: () =>
              isAlltSaman
                ? (window.location.href = `/${nationalId}/thjonusta/${subId}`)
                : (window.location.href = `/${nationalId}/reikningar`),
          },
        })}
        title={t('restrictions.otherBanner.title')}
        hasPingAlert
      />
    );

  return (
    <NotificationBanner
      icon="walletEmpty"
      color={ui?.serviceColor}
      title={t('restrictions.banner.title')}
      description={
        isStaffOrPayer
          ? t('restrictions.banner.description')
          : t('restrictions.banner.descriptionTwo')
      }
      eyebrowText={t('restrictions.banner.eyebrow')}
      hasPingAlert={hasPingAlert}
      {...(isStaffOrPayer &&
        !isShowingLiftForm && {
          mainButtonColored: {
            icon: 'longArrowRight',
            text: t('restrictions.banner.payButton'),
            onClick: () =>
              isAlltSaman
                ? (window.location.href = `/${nationalId}/thjonusta/${subId}`)
                : (window.location.href = `/${nationalId}/reikningar`),
          },
        })}
      {...(isStaffAndNotAlltSaman && {
        mainButtonWhite: {
          text: isShowingLiftForm
            ? t('restrictions.banner.back')
            : t('restrictions.banner.openButton'),
          icon: isShowingLiftForm ? 'longArrowLeft' : 'longArrowRight',
          onClick: () => setIsShowingLiftForm(!isShowingLiftForm),
        },
      })}
    >
      {isStaffOrPayer && !isShowingLiftForm && (
        <ContractDefaultsContainer backupContractId={contractId} />
      )}
      {isShowingLiftForm && (
        <Box display="flex" flexDirection="column" gap={2}>
          <Text variant="subHeading">{t('restrictions.otherBanner.title')}</Text>
          <Text>{t('restrictions.banner.openDescription')}</Text>
          <Box width="4/12">
            <MainButton
              dottedShadow="none"
              colorScheme={ui?.serviceColor}
              text={t('restrictions.banner.open')}
              icon="checkMark"
              onClick={() => handleRestrictionLift()}
            />
          </Box>
          {liftError && (
            <Text variant="pMediumBold" color="warning">
              {liftError}
            </Text>
          )}
        </Box>
      )}
    </NotificationBanner>
  );
};

export default inject('authentication', 'ui')(FiberRestrictions);
